package org.dromara.system.job;

import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.DeviceAlarm;
import org.dromara.system.domain.VariableAssociation;
import org.dromara.system.domain.protocol.SensorData;
import org.dromara.system.mapper.DeviceAlarmMapper;
import org.dromara.system.service.IVariableAssociationService;
import org.dromara.system.utils.DeviceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@JobExecutor(name = "getFireDevice")
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class getFireDevice {
    private final IVariableAssociationService variableAssociationService;
    public ExecuteResult jobExecute(JobArgs jobArgs) {
        RestTemplate restTemplate = new RestTemplate();
        DeviceUtils deviceUtils=new DeviceUtils(restTemplate);
        List<VariableAssociation> variableAssociations = new ArrayList<>();
        List<SensorData> sensorDataList=deviceUtils.getDeviceList();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        for (SensorData sensorData : sensorDataList) {
            VariableAssociation variableAssociation = new VariableAssociation();
            variableAssociation.setCode(String.valueOf(sensorData.getSensor()));
            variableAssociation.setStatus(1);
            String typeName = sensorData.getTypename() != null ? sensorData.getTypename() : String.valueOf(sensorData.getSensor());
            variableAssociation.setName(typeName);
            variableAssociation.setAlias(typeName);
            variableAssociation.setSource(7);
            variableAssociation.setValue(BigDecimal.valueOf(sensorData.getValue()));
            variableAssociation.setCreateBy(1L);
            try {
                Date timeDate = dateFormat.parse(sensorData.getTime());
                variableAssociation.setLastPing(timeDate); // 假设 VariableAssociation 类中有 setTime 方法
            } catch (ParseException e) {
                log.error("Failed to parse date: {}", sensorData.getTime(), e);
                variableAssociation.setLastPing(new Date());
            }
            variableAssociation.setCreateTime(new Date());
            variableAssociations.add(variableAssociation);
        }
        variableAssociationService.insertOrUpdateByBo(variableAssociations);
        return ExecuteResult.success("更新数据成功");
    }


}
